package com.ruoyi.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.util.security.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/** mp自动插入创建时间和修改时间
 * @author LiuXiaoYu
 * @date 2021/7/19- 16:41
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("自动填充创建和修改时间");
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime", new Date(),metaObject);
        if (Objects.nonNull(SecurityUtils.getUsername())){
            log.info("自动填充由谁创建和由谁更新");
            this.setFieldValByName("createBy", SecurityUtils.getUsername(),metaObject);
            this.setFieldValByName("updateBy",SecurityUtils.getUsername(),metaObject);
        }
        log.info("自动填充逻辑删除默认值");
        this.setFieldValByName("deleted",0,metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("自动填充修改时间");
        this.setFieldValByName("updateTime",new Date(),metaObject);
        try {
            if (Objects.nonNull(SecurityUtils.getUsername())){
                log.info("自动填充由谁更新");
                this.setFieldValByName("updateBy",SecurityUtils.getUsername(),metaObject);
            }
        }catch (Exception e){
            log.info("登录请求更新 updateBy字段是没有已经登录的用户名的");
        }

    }
}
